# -*- coding: utf-8 -*-s
import json
from pyquery import PyQuery
from export.distributors.b2b import B2b


class Mti(B2b):
    host = 'https://www.distri.mti.ua'
    catalog = {}

    def __init__(self):
        B2b.__init__(self)
        pass

    def handlerHtmlCatalog(self):
        self.browser.open(self.host)
        jQuery = PyQuery(self.browser.response().get_data())
        categories = jQuery('.catalog_menu').children()
        for category in categories:
            try:
                categories_ = jQuery(jQuery(category).children()[1]).children()
                for category_ in categories_:
                    categoryName = jQuery(category_).text()
                    categoryLink = jQuery(category_).children()[0].attrib['href']
                    self.catalog[categoryName] = self.catalog[categoryName] = self.handlerHtmlCategory(
                        categoryLink=categoryLink)
            except Exception:
                return json.dumps([self.catalog])
        return json.dumps([self.catalog])

    def handlerHtmlCategory(self, **kwargs):
        categoryLink = kwargs['categoryLink']
        jQuery = PyQuery(self.browser.open(self.host + categoryLink).get_data())
        productsLink = jQuery('.even a')
        products = []
        if productsLink:
            for productLink in productsLink:
                product = self.handlerHtmlProduct(link=productLink.attrib['href'])
                products.append(product)

    def handlerHtmlProduct(self, **kwargs):
        productLink = kwargs['link']
        jQuery = PyQuery(self.browser.open(self.host + productLink).get_data())
        attributesCode = jQuery('.table-striped tr')
        product = {}
        attributes = []
        for attributeCode in attributesCode:
            attr = jQuery(jQuery(attributeCode).children()[0]).text()
            if attr:
                attributes.append({attr: []})
        product['attrs'] = attributes
        return product




